package com.iwuyc.tools.commons.util.string;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class BufferUtil {
    private BufferUtil() {
    }

    /**
     * 创建一个ByteBuffer实例
     *
     * @param bytes 数据
     * @return ByteBuffer实例
     */
    public static ByteBuffer create(byte[] bytes) {
        return ByteBuffer.wrap(bytes);
    }

    /**
     * 根据字符串创建一个ByteBuffer实例
     *
     * @param data    数据
     * @param charset 编码
     * @return ByteBuffer实例
     */
    public static ByteBuffer create(CharSequence data, Charset charset) {
        final byte[] bytes = StringUtils.toBytes(data, charset);
        return ByteBuffer.wrap(bytes);
    }

    /**
     * 根据字符串创建一个ByteBuffer实例，使用默认字符集
     *
     * @param data 数据
     * @return ByteBuffer实例
     */
    public static ByteBuffer create(CharSequence data) {
        return create(data, null);
    }

    /**
     * 创建{@link CharBuffer}
     *
     * @param capacity 容量
     * @return {@link CharBuffer}
     * @see CharBuffer#allocate(int)
     */
    public static CharBuffer createCharBuffer(int capacity) {
        return CharBuffer.allocate(capacity);
    }


    /**
     * 读取指定区间的数据
     *
     * @param buffer {@link ByteBuffer}
     * @param start  开始位置
     * @param length 长度
     * @return bytes
     * @throws IndexOutOfBoundsException 如果buffer容量小于start+length
     */
    public static byte[] readBytes(ByteBuffer buffer, int start, int length) {
        if (buffer.capacity() < start + length) {
            throw new IndexOutOfBoundsException("buffer capacity is " + buffer.capacity()
                    + ", but start is " + start + ", length is " + length);
        }
        byte[] bs = new byte[length];
        buffer.get(bs, start, length);
        return bs;
    }

    /**
     * 读取指定长度的数据
     *
     * @param buffer 待读取的数据
     * @param length 长度
     * @return bytes
     * @throws IndexOutOfBoundsException 如果buffer容量小于length
     */
    public static byte[] readBytes(ByteBuffer buffer, int length) {
        return readBytes(buffer, 0, length);
    }

    /**
     * 读取剩余部分bytes<br>
     *
     * @param buffer ByteBuffer
     * @return bytes
     */
    public static byte[] readBytes(ByteBuffer buffer) {
        final int remaining = buffer.remaining();
        byte[] ab = new byte[remaining];
        buffer.get(ab);
        return ab;
    }

    /**
     * 读取剩余部分并转为字符串
     *
     * @param buffer  ByteBuffer
     * @param charset 编码
     * @return 字符串
     * @since 4.5.0
     */
    public static String readAsString(ByteBuffer buffer, Charset charset) {
        final byte[] bytes = readBytes(buffer);
        return StringUtils.fromBytes(bytes, charset);
    }
}
